package asset;

import java.util.ArrayList;
import java.util.List;

public class PC {
    private static int value = 0x3000;
    private static int imcur = 0;
    private static int imend = 0;
    private static boolean endSignal = false;
    private static boolean outputEnable = true;
    private static List<RegOrder> orders = new ArrayList<RegOrder>();

    public static void outConfig(boolean ifoutput) {
        outputEnable = ifoutput;
    }

    public static int getValue() {
        return value;
    }

    public static boolean isEndSignal() {
        return endSignal;
    }

    public static RegOrder getOrder() {
        return orders.get(imcur);
    }

    /**
     * load registered instruction, class RegOrder
     */
    public static void loadInst(RegOrder... regOrders) {
        for (RegOrder regOrder : regOrders) {
            orders.add(regOrder);
            imend++;
        }
    }

    /**PC value change */
    public static void next(int nextPc) throws Exception {
        value = nextPc;

        if ((value & 0b11) != 0) {
            throw new Exception(String.format("PC value %010x is illegal", value));
        }

        if (value < 0x3000 || value > 0x6ffc) {
            throw new Exception(String.format("PC value %#010x is wrong", value));
        }
        else {
            imcur = (value - 0x3000) >>> 2;
        }

        if (imcur > imend) {
            throw new Exception(String.format("PC value %#010x out of max im addr",value));
        }
        else if (imcur == imend) {
            endSignal = true;
        }
        else {
            endSignal = false;
        }
    }

    public static void next() throws Exception {
        if (outputEnable) {
            System.out.println("");
        }
        next(value + 4);
    }
}